package com.qfedu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.entity.ResponseData;
import com.qfedu.entity.Student;
import com.qfedu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;


    @RequestMapping("/getAllStudent")
    @ResponseBody
    public List<Student> getAllStudent(){

       return    studentService.findAllStudent();
    }


    /**
     * 接收分页数据
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/getAllStudentByPage")
    @ResponseBody
    public ResponseData<List<Student>> getAllStudentByPage(int page,int limit){


        // 开启分页
        PageHelper.startPage(page,limit);

        // 咱照分页查询
        List<Student> studentList =   studentService.findAllStudent();

        PageInfo<Student> pageInfo = new PageInfo<>(studentList);

        // 获取数据表中所有数据行数
        int count = (int) pageInfo.getTotal();

        ResponseData<List<Student>> responseData = new ResponseData<>();

        // 成功
        responseData.setCode(0);
        responseData.setMsg("success");
        responseData.setCount(count);
        responseData.setData(studentList);

        return responseData;
    }


    @RequestMapping("/deleteStudentById")
    @ResponseBody
    public ResponseData  deleteStudentById(int id){


       boolean result =  studentService.deleteStudentById(id);

       ResponseData responseData = new ResponseData();
       if (result){
           responseData.setMsg("success");
           responseData.setCode(0);// 0代表成功
       }else {
           responseData.setMsg("fail");
           responseData.setCode(1);// 1 代表失败
       }
       return responseData;
    }

    @RequestMapping("/updateStudent")
    @ResponseBody
    public ResponseData updateStudent(Student student){

       int num =  studentService.updateStudent(student);

        ResponseData responseData = new ResponseData();
       if (num>0){
           responseData.setMsg("success");
           responseData.setCode(0);// 0代表成功
       }else {
           responseData.setMsg("fail");
           responseData.setCode(1);// 1 代表失败
       }

       return responseData;
    }

}
